package mongoDB.group;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.mongodb.AggregationOutput;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;

/**
 * 
 * @Title: GroupByTest.java
 * @Package mongoDB group分组
 * @Description: db.appUser.aggregate([{"$group":{_id:"$userid",count:{$sum:1}}},{$sort:{count:-1}}])
 * @author 刘伟 15818570028@163.com
 * @date 2017年2月23日 上午11:28:25
 * @version V1.0
 */
public class GroupByTest {
	public static void main(String[] args) throws Exception {

		MongoClient mongo = new MongoClient(" 10.1.10.77", 10001);

		DB db = mongo.getDB("dc");

		DBCollection users = db.getCollection("user_start_app");

		test1(users);
		mongo.close();

	}

	/**
	 * 
	 * @Title: test1
	 * @Description: 过期方法 分组
	 * @param users
	 */
	private static void test1(DBCollection users) {
		AggregationOutput agout = users.aggregate(new BasicDBObject("$group",
				new BasicDBObject("_id", "$citycode").append("count", new BasicDBObject("$sum", 1))));
		Iterator<DBObject> results = agout.results().iterator();

		while (results.hasNext()) {
			DBObject obj = results.next();

			System.out.println(obj.get("_id") + " " + obj.get("count"));

		}
	}

	/**
	 * 
	 * @Title: test2
	 * @Description: 现在不过期原始分组实现
	 * @param users
	 */
	private static void test2(DBCollection users) {
		List<DBObject> pipeline = new ArrayList<DBObject>();
		BasicDBObject basicDBObject = new BasicDBObject("$group",
				new BasicDBObject("_id", "$userid").append("count", new BasicDBObject("$sum", 1)));
		pipeline.add(basicDBObject);
		AggregationOutput agout = users.aggregate(pipeline);
		Iterator<DBObject> results = agout.results().iterator();
		while (results.hasNext()) {
			DBObject obj = results.next();
			System.out.println(obj.get("_id") + " " + obj.get("count"));

		}
	}

}
